import resource from '../assets/data/resource.js'
import posts6 from '@/assets/data/posts6.json'
import { _fetch, cloneDeep, random } from '@/utils'
import { BASE_URL, FILE_URL } from '@/config'
import { useBaseStore } from '@/store/pinia'
import { axiosInstance } from '@/utils/request'
import MockAdapter from 'axios-mock-adapter'

const mock = new MockAdapter(axiosInstance)

// 获取服务器配置的函数（兼容浏览器和APK环境）
function getServerConfig() {
  try {
    // 尝试从localStorage读取
    if (typeof localStorage !== 'undefined') {
      const config = localStorage.getItem('serverConfig')
      return config ? JSON.parse(config) : {}
    }
    // 如果localStorage不可用，返回默认配置
    console.warn('localStorage不可用，使用默认API配置')
    return {}
  } catch (error) {
    console.error('读取服务器配置失败:', error)
    return {}
  }
}

// 获取API基础URL，优先使用本地存储的配置
function getApiBaseUrl() {
  const config = getServerConfig()
  // 添加调试日志
  console.log('获取API基础URL:', config.apiBaseUrl || 'http://192.168.50.166:8082')
  return config.apiBaseUrl || 'http://192.168.50.166:8082'
}

// 数据源配置（使用动态URL，每次调用都重新获取最新配置）
const getDataSources = () => {
  const currentApiUrl = getApiBaseUrl()
  console.log('动态获取数据源配置，当前API URL:', currentApiUrl)
  return {
    first: {
      name: '首页数据源',
      url: `${currentApiUrl}/api/data/files/douyin/first.md`,
      // 模拟数据范围
      dataRange: { start: 0, end: 844 }
    },
    second: {
      name: '首页2数据源', 
      url: `${currentApiUrl}/api/data/files/douyin/second.md`,
      // 模拟数据范围
      dataRange: { start: 844, end: 1688 }
    },
    third: {
      name: '首页3数据源',
      url: `${currentApiUrl}/api/data/files/douyin/third.md`,
      // 模拟数据范围
      dataRange: { start: 1688, end: 2532 }
    }
  }
}

// 为兼容现有代码，提供获取API基础URL的函数
function getApiBaseUrlValue() {
  return getApiBaseUrl()
}

// 动态获取API基础URL的函数（用于兼容现有代码）
function getApiBaseUrlDynamic() {
  return getApiBaseUrl()
}

// 动态获取数据源配置的函数（用于兼容现有代码）
function getDataSourcesDynamic() {
  return getDataSources()
}

function getPage2(params: any): { limit: number; offset: number; pageNo: number } {
  const offset = params.pageNo * params.pageSize
  const limit = params.pageNo * params.pageSize + params.pageSize
  return { limit, offset, pageNo: params.pageNo }
}

let allRecommendPosts = []
let userVideos = []
let allRecommendVideos = posts6.map((v: any) => {
  v.type = 'recommend-video'
  return v
})

// 存储不同数据源的视频数据
let dataSourceVideos = {
  first: [...allRecommendVideos], // 首页使用默认数据
  second: [], // 首页2数据
  third: []  // 首页3数据
}

// console.log('allRecommendVideos', allRecommendVideos)
// eslint-disable-next-line
const t = [
  {
    type: 'imgs',
    src: `https://imgapi.cn/bing.php`,
    author: {
      unique_id: 1,
      avatar_168x168: {
        url_list: []
      },
      avatar_300x300: {
        url_list: []
      },
      cover_url: [
        {
          url_list: []
        }
      ],
      white_cover_url: [
        {
          url_list: []
        }
      ]
    }
  }
  // {
  //   type: 'user',
  //   src: `https://imgapi.cn/bing.php`,
  //   author: {
  //     unique_id: 2,
  //     avatar_168x168: {
  //       url_list: []
  //     },
  //     avatar_300x300: {
  //       url_list: []
  //     },
  //     cover_url: [
  //       {
  //         url_list: []
  //       }
  //     ],
  //     white_cover_url: [
  //       {
  //         url_list: []
  //       }
  //     ]
  //   }
  // },
  // {
  //   type: 'img',
  //   src: `https://imgapi.cn/bing.php`,
  //   author: {
  //     unique_id: 3,
  //     avatar_168x168: {
  //       url_list: []
  //     },
  //     avatar_300x300: {
  //       url_list: []
  //     },
  //     cover_url: [
  //       {
  //         url_list: []
  //       }
  //     ],
  //     white_cover_url: [
  //       {
  //         url_list: []
  //       }
  //     ]
  //   }
  // }
]

// allRecommendVideos.unshift(...t)
// {
//   type: 'user-imgs',
//   src: `http://douyin.ttentau.top/0.mp4?vframe/jpg/offset/0/w/${document.body.clientWidth}`,
//   author: {
//     unique_id: uniqueId('list_')
//   }
// },
// {
//   type: 'user',
//   src: `http://douyin.ttentau.top/0.mp4?vframe/jpg/offset/0/w/${document.body.clientWidth}`,
//   author: {
//     unique_id: uniqueId('list_')
//   }
// },

// 异步加载数据源数据
async function loadDataSourceData(dataSource: string) {
  const baseStore = useBaseStore()
  // 每次调用时动态获取最新的数据源配置
  const currentDataSources = getDataSources()
  const sourceConfig = currentDataSources[dataSource as keyof typeof currentDataSources]
  
  if (!sourceConfig) {
    console.error(`数据源配置不存在: ${dataSource}`)
    return
  }
  
  try {
    console.log(`正在加载数据源 ${dataSource}，URL: ${sourceConfig.url}`)
    const response = await _fetch(sourceConfig.url)
    const data = await response.json()
    
    let userList = cloneDeep(baseStore.users)
    if (!userList.length) {
      await baseStore.init()
      userList = cloneDeep(baseStore.users)
    }
    
    // 处理数据并关联用户信息
    const processedData = data.map((w: any) => {
      w.type = 'recommend-video'
      const item: any = userList.find((a) => String(a.uid) === String(w.author_user_id))
      if (item) w.author = item
      return w
    })
    
    // 存储到对应数据源
    dataSourceVideos[dataSource as keyof typeof dataSourceVideos] = processedData
    
    console.log(`数据源 ${dataSource} 加载完成，数据量: ${processedData.length}`)
  } catch (error) {
    console.error(`加载数据源 ${dataSource} 失败:`, error)
    // 如果远程数据加载失败，使用模拟数据
    const { start, end } = sourceConfig.dataRange
    dataSourceVideos[dataSource as keyof typeof dataSourceVideos] = 
      allRecommendVideos.slice(start % allRecommendVideos.length, end % allRecommendVideos.length)
  }
}

// 加载所有数据源数据
async function fetchAllDataSources() {
  await loadDataSourceData('first')
  await loadDataSourceData('second') 
  await loadDataSourceData('third')
}

async function fetchData() {
  const baseStore = useBaseStore()
  return _fetch(`${getApiBaseUrlDynamic()}/api/data/files/douyin/first.md`).then((r) => {
    return r.json().then(async (v) => {
      let userList = cloneDeep(baseStore.users)
      if (!userList.length) {
        await baseStore.init()
        userList = cloneDeep(baseStore.users)
      }
      v = v.map((w) => {
        w.type = 'recommend-video'
        const item: any = userList.find((a) => String(a.uid) === String(w.author_user_id))
        if (item) w.author = item
        return w
      })
      allRecommendVideos = allRecommendVideos.concat(v)
    })
  })
}

//TODO 有个bug，一开始只返回了6条数据，但第二次前端传过来的pageNo是2了，就是会从第10条数据开始返回，导致中间漏了4条
export async function startMock() {
  // 支持多数据源的视频推荐API
  mock.onGet(/video\/recommended/).reply(async (config) => {
    const { start, pageSize, dataSource = 'first' } = config.params
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据
      targetVideos = allRecommendVideos
    }
    
    // 计算实际的数据范围
    const actualStart = Math.min(start, targetVideos.length - 1)
    const actualEnd = Math.min(start + pageSize, targetVideos.length)
    
    return [
      200,
      {
        data: {
          total: targetVideos.length,
          list: targetVideos.slice(actualStart, actualEnd)
        },
        code: 200,
        msg: '',
        dataSource: dataSource // 返回当前使用的数据源
      }
    ]
  })
  // 支持多数据源的长视频推荐API
  mock.onGet(/video\/long\/recommended/).reply(async (config) => {
    const { dataSource = 'first' } = config.params
    const page = getPage2(config.params)
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据（基于数据源的模拟数据）
      const currentDataSources = getDataSources()
      const sourceOffset = currentDataSources[dataSource as keyof typeof currentDataSources]?.dataRange.start || 0
      const sliceStart = sourceOffset % allRecommendVideos.length
      const sliceEnd = (sourceOffset + 110) % allRecommendVideos.length
      targetVideos = allRecommendVideos.slice(sliceStart, sliceEnd)
    }
    
    // 使用完整数据范围，移除110条限制
    const longVideoData = targetVideos
    
    return [
      200,
      {
        data: {
          total: longVideoData.length,
          list: longVideoData.slice(page.offset, page.limit)
        },
        code: 200,
        msg: '',
        dataSource: dataSource
      }
    ]
  })

  mock.onGet(/video\/comments/).reply(async (config) => {
    const videoIds = [
      '7260749400622894336',
      '7128686458763889956',
      '7293100687989148943',
      '6923214072347512068',
      '7005490661592026405',
      '7161000281575148800',
      '7267478481213181238',
      '6686589698707590411',
      '7321200290739326262',
      '7194815099381484860',
      '6826943630775831812',
      '7110263965858549003',
      '7295697246132227343',
      '7270431418822446370',
      '6882368275695586568',
      '7000587983069957383'
    ]
    let id = config.params.id
    if (!videoIds.includes(String(id))) {
      id = videoIds[random(0, videoIds.length - 1)]
    }
    const r2 = await _fetch(`${FILE_URL}/comments/video_id_${id}.md`)
    const v = await r2.json()
    if (v) {
      return [200, { data: v, code: 200 }]
    }
    return [200, { code: 500 }]
  })

  mock.onGet(/video\/private/).reply(async (config) => {
    const { dataSource = 'first' } = config.params
    const page = getPage2(config.params)
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据
      targetVideos = allRecommendVideos
    }
    
    return [
      200,
      {
        data: {
          total: 10,
          list: targetVideos.slice(100, 110).slice(page.offset, page.limit)
        },
        code: 200,
        msg: '',
        dataSource: dataSource
      }
    ]
  })

  mock.onGet(/video\/like/).reply(async (config) => {
    const { dataSource = 'first' } = config.params
    const page = getPage2(config.params)
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据
      targetVideos = allRecommendVideos
    }
    
    return [
      200,
      {
        data: {
          total: 150,
          list: targetVideos.slice(200, 350).slice(page.offset, page.limit)
        },
        code: 200,
        msg: '',
        dataSource: dataSource
      }
    ]
  })

  mock.onGet(/video\/my/).reply(async (config) => {
    const page = getPage2(config.params)
    if (!userVideos.length) {
      // let r = await fetch(BASE_URL + '/data/user-71158770.json')
      // let r = await fetch(BASE_URL + '/data/user-8357999.json')
      const r = await _fetch(BASE_URL + '/data/user_video_list/user-12345xiaolaohu.md')
      const list = await r.json()
      const baseStore = useBaseStore()
      const userList = cloneDeep(baseStore.users)

      userVideos = list.map((w) => {
        if (userList.length) {
          const item = userList.find((a) => String(a.uid) === String(w.author_user_id))
          if (item) w.author = item
        }
        return w
      })
    }

    return [
      200,
      {
        data: {
          pageNo: page.pageNo,
          total: userVideos.length,
          list: userVideos.slice(page.offset, page.limit)
        },
        code: 200,
        msg: ''
      }
    ]
  })

  mock.onGet(/video\/history/).reply(async (config) => {
    const { dataSource = 'first' } = config.params
    const page = getPage2(config.params)
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据
      targetVideos = allRecommendVideos
    }
    
    return [
      200,
      {
        data: {
          total: 150,
          list: targetVideos.slice(200, 350).slice(page.offset, page.limit)
        },
        code: 200,
        msg: '',
        dataSource: dataSource
      }
    ]
  })

  mock.onGet(/user\/collect/).reply(async (config) => {
    const { dataSource = 'first' } = config.params
    
    // 获取对应数据源的视频数据
    let targetVideos = dataSourceVideos[dataSource as keyof typeof dataSourceVideos] || dataSourceVideos.first
    
    if (!targetVideos || targetVideos.length === 0) {
      // 如果该数据源数据为空，使用默认数据
      targetVideos = allRecommendVideos
    }
    
    return [
      200,
      {
        data: {
          video: {
            total: 50,
            list: targetVideos.slice(350, 400)
          },
          music: {
            total: resource.music.length,
            list: resource.music
          }
        },
        code: 200,
        msg: '',
        dataSource: dataSource
      }
    ]
  })

  mock.onGet(/user\/video_list/).reply(async (config) => {
    const id = config.params.id
    const r2 = await _fetch(`${FILE_URL}/user_video_list/user-${id}.md`)
    const v = await r2.json()
    if (v) {
      return [200, { data: v, code: 200 }]
    }
    return [200, { code: 500 }]
  })

  mock.onGet(/user\/panel/).reply(async () => {
    const r2 = await _fetch(BASE_URL + '/data/users.md')
    const v = await r2.json()
    // let item = v.find(a => a.uid === '68310389333')
    // let item = v.find(a => a.uid === '59054327754')
    const item = v.find((a) => a.uid === '2739632844317827')
    if (item) {
      return [200, { data: item, code: 200 }]
    }
    return [200, { code: 500 }]
  })

  mock.onGet(/user\/friends/).reply(async () => {
    const r2 = await _fetch(BASE_URL + '/data/users.md')
    const v = await r2.json()
    return [200, { data: v, code: 200 }]
  })

  mock.onGet(/historyOther/).reply(async (config) => {
    const page = getPage2(config.params)
    return [
      200,
      {
        data: {
          pageNo: page.pageNo,
          total: 0,
          list: []
        },
        code: 200,
        msg: ''
      }
    ]
  })

  mock.onGet(/post\/recommended/).reply(async (config) => {
    const page = getPage2(config.params)

    if (!allRecommendPosts.length) {
      const r = await _fetch(BASE_URL + '/data/posts.md')
      allRecommendPosts = await r.json()
    }
    return [
      200,
      {
        data: {
          pageNo: page.pageNo,
          total: allRecommendPosts.length,
          list: allRecommendPosts.slice(0, 1000).slice(page.offset, page.limit)
        },
        code: 200,
        msg: ''
      }
    ]
  })

  mock.onGet(/shop\/recommended/).reply(async (config) => {
    const page = getPage2(config.params)

    const r2 = await _fetch(BASE_URL + '/data/goods.md')
    const v = await r2.json()
    return [
      200,
      {
        data: {
          total: v.length,
          list: v.slice(page.offset, page.limit)
        },
        code: 200
      }
    ]
  })

  // 加载所有数据源数据
  await fetchAllDataSources()
  
  // 原有的fetchData保持兼容性
  setTimeout(fetchData, 1000)
}
